package com.itheima.health.service.impl;

import com.itheima.health.dao.*;
import com.itheima.health.pojo.*;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

@DubboService
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    RolePermissionMapper rolePermissionMapper;
    @Autowired
    PermissionMapper permissionMapper;

    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    @Override
    public User findByUserName(String username) {
        log.info("用户登录接口"+username);
        //原生mybatis
        User user = userMapper.findByUserName(username);
        //根据用户id查角色
        List<Role> roles = roleMapper.findByUserId(user.getId());
        user.getRoles().addAll(roles);
        for (Role role : roles) {
            //查询权限
            List<Permission> permissions=permissionMapper.findByRoleId(role.getId());
            role.getPermissions().addAll(permissions);
        }
        return user;

        //tkmybatis
        //查询封装用户角色
        /* User user = new User();
        user.setUsername(username);
        User user1 = userMapper.selectOne(user);

        UserRole userRole = new UserRole();
        userRole.setUserId(user1.getId());
        List<UserRole> userRoleList = userRoleMapper.select(userRole);
        ArrayList<Integer> roleidList = new ArrayList<>();
        for (UserRole role : userRoleList) {
            roleidList.add(role.getRoleId());
        }
        HashSet<Role> roles = new HashSet<>();
        for(Integer roleid : roleidList) {
            Role role = roleMapper.selectByPrimaryKey(roleid);
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleid);
            List<RolePermission> rolePermissionList = rolePermissionMapper.select(rolePermission);
            ArrayList<Integer> permissionids =  new ArrayList<>();
            for (RolePermission rolePermission1 : rolePermissionList) {
                permissionids.add(rolePermission1.getPermissionId());
            }
            HashSet<Permission> permissions = new HashSet<>();
            for (Integer permissionid : permissionids) {
                Permission permission = permissionMapper.selectByPrimaryKey(permissionid);
                permissions.add(permission);
            }
            role.setPermissions(permissions);
            log.info("封装后的role"+role);
            roles.add(role);
        }
        user1.setRoles(roles);
        log.info("封装后的user"+user1);
        return user1;*/
    }
}
